const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()


const views = require('koa-views')
const co = require('co')
const convert = require('koa-convert')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')
const session = require('koa-session2')


const config = require('./config')
const routes = require('./routes')

const cors = require('koa2-cors')
const { log } = require('console')
const port = process.env.PORT || config.port

// error handler
onerror(app)

// middlewares
app.use(bodyparser())
  .use(json())
  .use(logger())
  .use(require('koa-static')(__dirname + '/public'))
  .use(views(path.join(__dirname, '/views'), {
    options: { settings: { views: path.join(__dirname, 'views') } },
    map: { 'njk': 'nunjucks' },
    extension: 'njk'
  }))
  .use(session({
    key:'didi'
  }))
  .use(cors())
  .use(router.routes())
  .use(router.allowedMethods())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - $ms`)
})
console.log(1)

router.get('/banyuan', async (ctx, next) => {
  // ctx.body = 'Hello World'
  // ctx.state = {
  //   title: 'Koa2'
  // }
  // await ctx.render('index', ctx.state)
  // * Request请求体
  const { username, password, repassword } = ctx.request.query
  // console.log('username: ', username)
  // console.log('password: ', password)
  // console.log('repassword: ', repassword)

  const usernameReg = /^[0-9a-zA-Z_-]{4,16}$/
  const passwordReg = /^[0-9a-zA-Z_]{8,15}$/

  let error = {
    status: 'success'
  }

  if (usernameReg.test(username) && passwordReg.test(password) && password === repassword) {
    error.status = 'success'
  }

  if (!usernameReg.test(username)) {
    error.usernameError = '用户名不合法'
  }

  if (!passwordReg.test(password)) {
    error.passwordError = '密码不合法'
  }
  if (password !== repassword) {
    error.repasswordError = '密码两次输入不正确'
  }

  ctx.response.body = error

  // * Response回复
  // ctx.response.body = 'banyuan'
})

router.post('/banyuan', (ctx, next) => {
  const { username, password, repassword } = ctx.request.query
  // console.log('username: ', username)
  // console.log('password: ', password)
  // console.log('repassword: ', repassword)

  const usernameReg = /^[0-9a-zA-Z_-]{4,16}$/
  const passwordReg = /^[0-9a-zA-Z_]{8,15}$/

  let error = {}

  if (usernameReg.test(username) && passwordReg.test(password) && password === repassword) {
    error.status = 'success'
  }

  if (!usernameReg.test(username)) {
    error.usernameError = '用户名不合法'
  }

  if (!passwordReg.test(password)) {
    error.passwordError = '密码不合法'
  }
  if (password !== repassword) {
    error.repasswordError = '密码两次输入不正确'
  }

  ctx.response.body = error
})

router.post('/test', async (ctx, next) => {
  await sleep(5000)
  ctx.response.body = {
    status: 'success'
  }
})

function sleep(time) {
  return new Promise((res) => {
    setTimeout(() => {
      res()
    }, time)
  })
}
// router.get('/name', async (ctx, next) =>{
//   await sleep(2000),
//   const { name } = ctx.request.query
//   const array = [didi,111]
//   let date = {
//     start : 'success'
//   }
//   if(array.indexOf)
    
// }
router.get('/keyword', async (ctx, next) =>{
  const { keyword } = ctx.request.query
  console.log(keyword)
  const array = ['didi','didi111','11234','111','fsarw','abcd123','33333']
  let newArr = []

  array.forEach((item)=>{
    if(item.includes(keyword)) {
      newArr.push(item)
      console.log('item: ', item)
    }
  })

  ctx.response.body = newArr
  console.log('newArr==> ', newArr)

})
router.get('/form', async (ctx, next) => {
  const { username, password, repassword } = ctx.request.query
  const usernameReg = /^[0-9a-zA-Z_-]{4,16}$/
  const passwordReg = /^[0-9a-zA-Z_]{8,15}$/
  let error = {
    status: 'success'
  }
  if (usernameReg.test(username) && passwordReg.test(password) && password === repassword) {
    error.status = 'success'
  }
  if (!usernameReg.test(username)) {
    error.usernameError = '用户名不合法'
  }
  if (!passwordReg.test(password)) {
    error.passwordError = '密码不合法'
  }
  if (password !== repassword) {
    error.repasswordError = '密码两次输入不正确'
  }
  ctx.response.body = error
})
router.get('/name', async (ctx, next) => {
  const { username} = ctx.request.query

  const usernameReg = /^[0-9a-zA-Z_-]{4,16}$/
  const passwordReg = /^[0-9a-zA-Z_]{8,15}$/

  let data = {
    status:'success'
  }
  const arr = ['lucy','lily','isen','123']

  arr.forEach((item) => {
    if(item === username) {
      data.status = 'failed'
    }
  })

  // let error = {
  //   status: 'success'
  // }
  // if (usernameReg.test(username) && passwordReg.test(password) && password === repassword) {
  //   error.status = 'success'
  // }
  // if (!usernameReg.test(username)) {
  //   error.usernameError = '用户名不合法'
  // }
  // if (!passwordReg.test(password)) {
  //   error.passwordError = '密码不合法'
  // }
  // if (password !== repassword) {
  //   error.repasswordError = '密码两次输入不正确'
  // }
  ctx.response.body = data
})
// router.get('/form', async (ctx, next) =>{
//   const { form } = ctx.request.query
//   console.log(form)
//   const nameArray = ['lucy','tom','isen','lily']
//   let newArr = []

//   array.forEach((item)=>{
//     if(() {
//       newArr.push(item)
//       console.log('item: ', item)

//     }
//   })


//   ctx.response.body = newArr
//   console.log('newArr==> ', newArr)

// })

router.get('/getUserInfo' , async (ctx,next)=>{
  await ctx.render('userinfo')
  
})
router.get('/userInfo',async (ctx,next)=>{
  const{ name,age,gender } = ctx.request.query
  await ctx.render('userInfo',{ name })
})
router.get('/think',async(ctx,next)=>{
  // const { data } = ctx.request.query

  // let arr = ['123', '半圆', '教育', '12434', '12生肖']
  // let newArr = []

  // arr.forEach((item) => {
  //   if (item.includes(data)) {
  //     newArr.push(item)
  //   }
  // })
  await ctx.render('think')
  // ctx.response.body = newArr
})

router.get('/thinkk',async (ctx,next)=>{
  const { keyword } = ctx.request.query
  console.log(keyword)
  const array = ['didi','didi111','11234','111','fsarw','abcd123','33333']
  let newArr = []
  array.forEach((item)=>{
    if(item.includes(keyword)) {
      newArr.push(item)
      console.log('item: ', item)
    }
  })
  ctx.response.body = newArr
  console.log('newArr==> ', newArr)
})
router.get('/work',async(ctx,next)=>{
  await ctx.render('singin')
})
router.get('/singin',async(ctx,next)=>{
  const { username,password,repassword,age, } = ctx.request.query

  const usernameReg = /^[0-9a-zA-Z_-]{4,16}$/
  const passwordReg = /^[0-9a-zA-Z_]{8,15}$/

  let data = {
    status:'success'
  }
  const arr = ['lucy','lily','isen','123']

  arr.forEach((item) => {
    if(item === username) {
      data.status = 'failed'
    // }else if(Number(age < 0) || Number((age) >120)){
    //   data.status = 'falied'
    //   data.massage = '用户年龄不符合规则'
    }
    // ctx.response.body = data
  })
  
  await ctx.render('singin')
})


router.get('/nameRegist',async(ctx)=>{
  // const { username } = ctx.request.query
  // const nameArray = ['lucy','tom','isen','lily']
  // // const username = ctx.cookies.get('user')
  // if(username){
  //   data.status = 'failed'
  // } else{
  //   ctx.redirect('/passwordRegist')
  // }
  // ctx.response.body = data
  await ctx.render('nameRegist')
})

router.get('/checkUsername',(ctx)=>{
  const { name } = ctx.request.query
  const nameArray = ['lucy','tom','isen','lily']
  let data = {
    status : 'success'
  }
  if(nameArray.indexOf(name) > 0){
    data.status = 'failed'
  }
  ctx.response.body = data
})

router.get('/passwordRegist', async (ctx, next) => {
  await ctx.render('passwordRegist')
})

router.get('/userinfoRegist', async (ctx, next) => {
  await ctx.render('userinfoRegist')
})

router.get('/cookie', async (ctx, next) => {
  // ctx.body = 'Hello World'
  // ctx.session.refresh()
  // ctx.session.name = 'isen2222'
  const user = ctx.cookies.get('user')

  console.log('user ===>',user)
  if(user){
    await ctx.render('cookie')
  }else{
    ctx.redirect('/login')
  }
  
})
router.get('/login', async (ctx, next) => {
  await ctx.render('login')
})
router.post('/userLogin',(ctx)=>{

  const { name , password } = ctx.request.body

  let data = { name,password }

  ctx.cookies.set('user',JSON.stringify(data))
  ctx.session.name = 'isen'
  // console.log('JSON.stringify(data): ', string)
  // console.log(typeof string)
  
  // ctx.cookies.set('user',data)

  ctx.response.body = {
    name , password 
  }
})
router.post('/test',(ctx)=>{

  // const user = ctx.cookies.get('user')
  // const local = ctx.cookies.get('local')
  // console.log('local: ', local)
  console.log('ctx.session.name ===>',ctx.session.name)
  // console.log('user ===>',user)
  // let data = JSON.parse(user)
  // console.log('data: ', data)
  // console.log(data.name)
  // console.log('user ===>',typeof user)

  ctx.response.body = {
    
  }
})
routes(router)
app.on('error', function (err, ctx) {
  console.log(err)
  logger.error('server error', err, ctx)
})

module.exports = app.listen(config.port, () => {
  console.log(`Listening on http://localhost:${config.port}`)
})
